#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
import json
import uuid
import os
from repository import models
from utils.custom_encoder import JsonCustomEncoder
from utils.pagination import Page
from utils import img_check
from forms import backend_forms
from ..auth.auth import check_login


@check_login
def base_info(request):
    """博主个人信息"""
    user_obj = models.UserInfo.objects.filter(nid=request.session.get('nid')).first()

    if request.method == "GET":
        try:
            blog_obj = user_obj.blog
        except Exception:
            blog_obj = None
        return render(request, 'backend_base_info.html', {'user_obj': user_obj, 'blog_obj': blog_obj})

    elif request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}

        form_obj = backend_forms.BaseInfoForm(request, request.POST)
        if form_obj.is_valid():
            user_obj.nickname = form_obj.cleaned_data['nickname']
            user_obj.avatar = form_obj.cleaned_data['avatar']
            try:
                blog_obj = user_obj.blog
            except Exception:
                blog_obj = models.Blog.objects.create(title=request.POST.get('blog_title'),
                                           site=request.POST.get('blog_url'),
                                           theme=request.POST.get('blog_theme'),
                                           user_id=request.session.get('nid'))
                request.session['blog_nid'] = blog_obj.nid
            else:
                blog_obj.title = request.POST.get('blog_title')
                blog_obj.site = request.POST.get('blog_url')
                blog_obj.theme = request.POST.get('blog_theme')
                blog_obj.save()
            user_obj.save()
            res_dict['status'] = True
        else:
            res_dict['errors'] = form_obj.errors.as_data()
            res_dict['status'] = False

        return HttpResponse(json.dumps(res_dict, cls=JsonCustomEncoder))




@check_login
def upload_avatar(request):
    """上传头像"""
    file_obj = request.FILES.get('avatarImg')
    file_extension = file_obj.name.split('.')[-1]
    saved_filename = str(uuid.uuid1()) + '.' + file_extension
    file_path = os.path.join('static', 'upload', 'avatar', saved_filename)
    f = open(file_path, 'wb')
    for item in file_obj.chunks():
        f.write(item)
    f.close()

    if img_check.is_valid_image(file_path):    # 判断上传的是否是图片
        img_src = '/static/upload/avatar/' + saved_filename
    else:
        img_src = '/static/upload/avatar/default.png'
        os.remove(file_path)

    res_data = {'status': 'ok', 'img_src': img_src}
    return HttpResponse(json.dumps(res_data))

